package com.example.onlinemarket.service;

import com.example.onlinemarket.dao.UserDao;
import com.example.onlinemarket.bean.Page;
import com.example.onlinemarket.bean.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.stream.IntStream;

@Service
public class UserService {
    private UserDao userDao;
    @Autowired
    public void setUserDao(UserDao userDao){
        this.userDao = userDao;
    }

    private final String path = System.getProperty("user.dir")+"\\src\\main\\resources\\static\\img\\tempUserImg.jpg";

    /**
     *
     * @param userName 用户名
     * @param password 密码
     * @return 登录的User对象
     */
    //登录
    public User canUserLogin(String userName, String email, String password){
        //尝试用用户名+密码登录
        Boolean flag1 = userDao.canUserLoginByUserName(userName, password);
        //尝试用邮箱+密码登录
        Boolean flag2 = userDao.canUserLoginByEmail(email, password);
        //根据成功的方式选择获取用户数据的方式
        if(flag1)
            return userDao.getUserByName(userName);
        else if(flag2)
            return userDao.getUserByEmail(email);
        else
            //若登录失败则返回null
            return null;
    }

    public boolean isEmailExist(String email){
        return userDao.checkEmailExist(email);
    }

    //判断用户名为userName的用户是否存在
    public boolean isUserNameExist(String userName){
        return userDao.checkUserNameExist(userName);
    }

    //按userName更新用户头像
    public int updateUserImg(String userName, InputStream is){
        return userDao.updateUserHeadImg(userName, is);
    }

    //注册新用户，返回值为1表示注册成功
    public int register(User user){
        if(userDao.addUser(user)>0)
            return addImg4NewUser(user.getUserName());
        return -1;
    }

    //注册(Service层)
    public String canUserRegister(User user){
        //检查用户名是否存在
        if (!isUserNameExist(user.getUserName())) {
            int res = register(user);
            if (res > 0) //为用户添加临时头像
                addImg4NewUser(user.getUserName());
            return res>0?"注册成功":"注册失败，请稍候重试";
        }else
            return "用户名已存在";
    }

    private int addImg4NewUser(String userName) {
        InputStream is = null;
        try {
            is = new FileInputStream(path);
            return updateUserImg(userName, is);
        } catch (FileNotFoundException e) { e.printStackTrace(); }finally {
            if (is != null)
                try { is.close(); } catch (IOException e) { e.printStackTrace(); }
        }
        return -1;
    }

    public User getUserByName(String userName){
        return userDao.getUserByName(userName);
    }

    public boolean updateUserInfoWithImg(User user,InputStream is){
        int res = userDao.updateUserInfoWithImg(user, is);
        boolean flag = res > 0;
        System.out.println(flag?"更新成功":"更新失败");
        return flag;
    }

    public boolean updateUserInfoWithoutImg(User user){
        int res = userDao.updateUserInfoWithoutImg(user);
        boolean flag = res > 0;
        System.out.println(flag?"更新成功":"更新失败");
        return flag;
    }


    public Integer checkForUserSearching(String searchContent) {
        return userDao.checkForUserSearching(searchContent);
    }

    public List<User> searchForUser(String searchContent, Integer recorded, Integer pageSize) {
        return userDao.searchForUserByPages(searchContent, recorded, pageSize);
    }

    //商家搜索
    public Model userSearch(Model model, Integer currentPage, Integer pageSize, String searchContent) {
        String msg = "不存在名为"+ searchContent +"的商家!";
        searchContent = "%"+ searchContent +"%";
        Integer count = checkForUserSearching(searchContent);
        if(count>0) {//若存在查询记录
            int[] pageNum = null;
            Page page = new Page(currentPage, pageSize, count);
            //分页查询卖家
            List<User> shops = searchForUser(searchContent, page.getPageSize()*(page.getCurrentPage()-1), page.getPageSize());
            //根据总页数生成合适的数组
            if (page.getTotalPages()>1) {
                pageNum = IntStream.range(1, page.getTotalPages() + 1).toArray();
            }else{
                pageNum = IntStream.range(1, 2).toArray();
            }
            model.addAttribute("shops", shops);
            model.addAttribute("pageNums", pageNum);
            model.addAttribute("pageSize",pageSize);
            model.addAttribute("totalRecords", count);
            model.addAttribute("totalPages", page.getTotalPages());
        }else{//若不存在查询记录
            model.addAttribute("msg", msg);
            model.addAttribute("pageSize",0);
            model.addAttribute("totalRecords", 0);
            model.addAttribute("totalPages", 0);
        }
        return model;
    }

    public String getUserNameByUserId(Integer shopId) {
        return userDao.getUserNameById(shopId);
    }

    public User getUserById(Integer userId) {
        return userDao.getUserById(userId);
    }

    public boolean updateUserAddress(Integer userId, String address) {
        return userDao.updateUserAddress(userId, address);
    }

    public boolean updateUserAddress(String userName, String address) {
        return userDao.updateAddress(userName, address);
    }

    public boolean updateUserPassword(String userName, String password) {
        return userDao.updateUserPassword(userName, password);
    }

    public boolean updateUserEmail(String userName, String email) {
        return userDao.updateUserEmail(userName, email);
    }

    public boolean updatePayPassword(int userId, String payPassword) {
        return userDao.updatePayPassword(userId, payPassword);
    }
}
